package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.models.BatchUpdateDeviceNicknameRequest;
import com.aliyun.iot20180120.models.BatchUpdateDeviceNicknameResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-02
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 查询产品详情
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device)?1:0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device)?1:0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id)?1:0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST,
                JSONUtil.toJsonStr(response.getProducts()),
                60 * 60 * 24 + (int) Math.random() * 100, TimeUnit.SECONDS);
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        //如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {

        //1.检查设备名称是否重复
        //1.1 构建LambdaQueryWrapper对象
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        //1.2 设置设备名字筛选条件
        queryWrapper.eq(Device::getDeviceName,deviceDto.getDeviceName());
        //1.3 执行查询，获取查询匹配的个数，个数大于0，说明已存在，抛出异常，提示设备名称重复
        if (count(queryWrapper) > 0) {
            log.error("注册设备失败：设备名称 【{}】 重复",deviceDto.getDeviceName());
            throw new RuntimeException("注册设备失败：设备名称 【" + deviceDto.getDeviceName() + "】 重复");
        }

        //2.检查设备标识码是否重复
        //2.1 LambdaQueryWrapper对象清除上面的筛选条件（clear方法）
        queryWrapper.clear();
        //2.2 设置设备设备标识码筛选条件
        queryWrapper.eq(Device::getNodeId,deviceDto.getNodeId());
        //2.3 执行查询，获取查询匹配的个数，个数大于0，说明已存在，抛出异常，提示设备标识码重复
        if (count(queryWrapper) > 0) {
            log.error("注册设备失败：设备标识码 【{}】 重复",deviceDto.getNodeId());
            throw new RuntimeException("注册设备失败：设备标识码 【" + deviceDto.getNodeId() + "】 重复");
        }

        //3.检查同一位置是否绑定了相同的产品
        //1.1 LambdaQueryWrapper对象清除上面的筛选条件（clear方法）
        queryWrapper.clear();
        //1.2 设置筛选条件：binding_location，location_type,physical_location_type,product_key查询有数据代表同一位置绑定了相同产品的设备
        queryWrapper.eq(Device::getBindingLocation,deviceDto.getBindingLocation())
                .eq(Device::getLocationType,deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey,deviceDto.getProductKey());
        //1.3 执行查询，获取查询匹配的个数，个数大于0，说明已存在，抛出异常，提示设同一位置绑定了相同产品的设备
        if (count(queryWrapper) > 0){
            log.error("注册设备失败：同一位置绑定了相同产品的设备");
            throw new RuntimeException("注册设备失败：同一位置绑定了相同产品的设备");
        }

        //4.项目华为IOT平台注册设备
        //4.1 请求参数对象AddDeviceRequest对象
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        //4.2 请求体参数对象AddDevice对象
        AddDevice addDevice = new AddDevice();
        //设备标识码 node_id,device_name,product_id
        addDevice.withNodeId(deviceDto.getNodeId())
                .withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey());

        //实例AuthInfo对象，封装secret（自己生成唯一值）
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-","");
        authInfo.withSecret(secret);
        //AddDevice对象封装AuthInfo对象(withAuthInfo)
        addDevice.withAuthInfo(authInfo);

        //AddDeviceRequest对象封装AddDevice对象（withBody）
        addDeviceRequest.withBody(addDevice);
        //4.3 执行请求，获取响应结果AddDeviceResponse对象
        AddDeviceResponse addDeviceResponse = null;
        try {
            addDeviceResponse  = client.addDevice(addDeviceRequest);
        } catch (Exception e) {
            log.error("物联网平台-注册设备失败："+e.getMessage());
            throw new RuntimeException("注册设备失败："+e.getMessage());
        }
        //4.4 判断响应状态为是否为200,如果不是抛出异常，提示“物联网平台-注册设备失败”
        if (addDeviceResponse.getHttpStatusCode() != 201) {
            log.error("物联网平台-注册设备失败");
            throw new RuntimeException("注册设备失败：物联网平台-注册设备失败");
        }
        //4.5 提示设备注册成功
        log.info("物联网平台-注册设备【{}】成功", deviceDto.getDeviceName());

        //5.本地保存设备数据到数据库中
        //5.1 将前端传递过来的deviceDto对象数据封装赋值给Device对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //5.2 补全数据
        //iot_id 从AddDeviceResponse对象中获取
        device.setIotId(addDeviceResponse.getDeviceId());
        //secret
        device.setSecret(secret);
        //判断是否是随身设备，如果是，物理位置类型为-1
        if(device.getLocationType()==0){
            device.setPhysicalLocationType(-1);
        }
        //5.3 插入数据库
        try {
            save(device);
        } catch (Exception e) {
            //TODO 远程调用华为IOT删除设备(作业)，如果这里删除失败，人工接入，到IOT平台找到对应设备删除。
            log.error("注册设备失败："+e.getMessage());
            throw new RuntimeException("注册设备失败，原因："+e.getMessage());
        }
    }

    /**
     * 查询设备详情
     *
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }

        //调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备详情，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        //属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceVo.setActiveTime(activeTime);
        }

        return deviceVo;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isEmpty(shadow)){
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String,Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime);
            list.add(map);
        });

        return AjaxResult.success(list);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceNickName(Device device) {

        // 1.修改数据库中的信息
        updateById(device);

        // 2.修改IOT平台中的数据
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> list = new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo deviceNickNameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        // 封装条件数据
        deviceNickNameInfo.setIotId(device.getIotId());
        list.add(deviceNickNameInfo);

        request.setDeviceNicknameInfo(list);

        BatchUpdateDeviceNicknameResponse response;
        try {
            // TODO 这个API更新了，调用失败，临时注释
//            response = client.updateDeviceNickname(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除设备信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteDevice(String deviceId)
    {
        // 通过设备id删除设备
        remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));

        // 删除物联网中的数据
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(aliIoTConfigProperties.getIotInstanceId());
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("IOT调用，删除设备失败");
        }

        return 1;
    }
}
